package com.ihm.projetihm_v1.activity.photo.listener;

import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;

import com.ihm.projetihm_v1.activity.photo.PhotoActivity;
import com.ihm.projetihm_v1.nf.LinkedPhoto;

public class ImageListener
		implements OnTouchListener
{
	private static final int C_MINIMAL_DISTANCE = 20;
	
	private PhotoActivity photoActivity;

	private float memXStart, memYStart;

	public ImageListener(PhotoActivity photoActivity) {
		this.photoActivity = photoActivity;
	}

	private void onClick() {
		this.photoActivity.inverseArrowButtonVisibility();
	}

	@Override
	public boolean onTouch(View v, MotionEvent event) {
		switch (event.getAction()) {
		case MotionEvent.ACTION_DOWN: // code is executed after the user touch
										// on the screen
			// Memoriser la position de depart
			this.memXStart = event.getX();
			this.memYStart = event.getY();
			break;

		case MotionEvent.ACTION_MOVE: // code is executed when user move the
										// finger on the screen
			break;

		case MotionEvent.ACTION_UP: // code is executed after the user release
									// the touch on the screen
			// Memoriser la position d'arrivee
			float xEnd = event.getX();
			float yEnd = event.getY();

			float dx = xEnd - this.memXStart;
			float dy = yEnd - this.memYStart;
			float distance = (float) Math.sqrt(dx * dx + dy * dy);

			if (distance >= C_MINIMAL_DISTANCE) {
				LinkedPhoto.RELATION_TYPE relationType = getRelationTypeFromCoord(
						this.memXStart, this.memYStart, xEnd, yEnd);
				this.photoActivity.goTo(relationType);
			} else {
				this.onClick();
			}

			break;
		}
		return true;
	};

	private static LinkedPhoto.RELATION_TYPE getRelationTypeFromCoord(
			float xstart, float ystart, float xend, float yend) {
		float dx = Math.abs(xend - xstart);
		float dy = Math.abs(yend - ystart);

		if (dx > dy) { // gauche ou droite
			if (xend < xstart) {
				return LinkedPhoto.RELATION_TYPE.EAST;
			} else {
				return LinkedPhoto.RELATION_TYPE.WEST;
			}
		} else { // haut ou bas
			if (yend < ystart) {
				return LinkedPhoto.RELATION_TYPE.SOUTH;
			} else {
				return LinkedPhoto.RELATION_TYPE.NORTH;
			}
		}
	}

}
